<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品分类" prop="categoryId">
        <el-cascader
          @change="cascaderHandleQuery"
          v-model="queryParams.categoryId"
          :options="options"
          :props="{ checkStrictly: true }"
          clearable></el-cascader>
      </el-form-item>
      <el-form-item label="商品名称" prop="goodsName">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入商品名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['goods:goods:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['goods:goods:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['goods:goods:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['goods:goods:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="goodsList" @selection-change="handleSelectionChange">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="商品分类:" class="demo_label__label__font width-70 height-250">
              <div class="demo_label__label__font__span demo_label__label__font__span__width-250">
                <span>{{ props.row.categoryNames }}</span>
              </div>
            </el-form-item>
            <el-form-item label="商品市场价格:" class="demo_label__label__font width-95">
              <div class="demo_label__label__font__span">
                <span>{{ props.row.price }}</span>
              </div>
            </el-form-item>
            <el-form-item label="成本价:" class="demo_label__label__font width-55">
              <div class="demo_label__label__font__span">
                <span>{{ props.row.costPrice }}</span>
              </div>
            </el-form-item>
            <el-form-item label="收藏:" class="demo_label__label__font width-45">
              <div class="demo_label__label__font__span">
                <span>{{ props.row.numberFavorites }}</span>
              </div>
            </el-form-item>
            <el-form-item label="虚拟销量:" class="demo_label__label__font width-70">
              <div class="demo_label__label__font__span">
                <span>{{ props.row.quantitySold }}</span>
              </div>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>

      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品ID" align="center" prop="goodsId" />
      <el-table-column label="商品图" align="center" width="80">
        <template v-slot="scope">
          <el-image
            :src="scope.row.mainImgUrl"
            fit="fill"
            width="80%">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="goodsName" width="250"/>
      <el-table-column label="商品类型" align="center" prop="type" />
      <el-table-column label="售价" align="center" prop="sellingPrice" />
      <el-table-column label="销量" align="center" prop="sales" />
      <el-table-column label="库存量" align="center" prop="stock" />
      <el-table-column label="排序" align="center" prop="orderNum" />
      <el-table-column label="状态" align="center" key="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['goods:goods:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['goods:goods:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品编号" prop="goodsSn">
          <el-input v-model="form.goodsSn" placeholder="请输入商品编号" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品单位" prop="goodsUnit">
          <el-input v-model="form.goodsUnit" placeholder="请输入商品单位" />
        </el-form-item>
        <el-form-item label="商品规格" prop="goodsSpecification">
          <el-input v-model="form.goodsSpecification" placeholder="请输入商品规格" />
        </el-form-item>
        <el-form-item label="售价" prop="sellingPrice">
          <el-input v-model="form.sellingPrice" placeholder="请输入售价" />
        </el-form-item>
        <el-form-item label="成本价" prop="costPrice">
          <el-input v-model="form.costPrice" placeholder="请输入成本价" />
        </el-form-item>
        <el-form-item label="原价" prop="price">
          <el-input v-model="form.price" placeholder="请输入原价" />
        </el-form-item>
        <el-form-item label="库存量" prop="stock">
          <el-input v-model="form.stock" placeholder="请输入库存量" />
        </el-form-item>
        <el-form-item label="重量(KG)" prop="weight">
          <el-input v-model="form.weight" placeholder="请输入重量(KG)" />
        </el-form-item>
        <el-form-item label="体积(m³)" prop="volume">
          <el-input v-model="form.volume" placeholder="请输入体积(m³)" />
        </el-form-item>
        <el-form-item label="商品详情" prop="goodsDetails">
          <el-input v-model="form.goodsDetails" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="已售数量" prop="quantitySold">
          <el-input v-model="form.quantitySold" placeholder="请输入已售数量" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
        </el-form-item>
        <el-form-item label="商品推荐" prop="goodsRecommend">
          <el-input v-model="form.goodsRecommend" placeholder="请输入商品推荐" />
        </el-form-item>
        <el-form-item label="商品浏览量" prop="goodsViews">
          <el-input v-model="form.goodsViews" placeholder="请输入商品浏览量" />
        </el-form-item>
        <el-form-item label="商品访客数" prop="numberVisitors">
          <el-input v-model="form.numberVisitors" placeholder="请输入商品访客数" />
        </el-form-item>
        <el-form-item label="下单件数" prop="numberOrdered">
          <el-input v-model="form.numberOrdered" placeholder="请输入下单件数" />
        </el-form-item>
        <el-form-item label="收藏数" prop="numberFavorites">
          <el-input v-model="form.numberFavorites" placeholder="请输入收藏数" />
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item>
        <el-form-item label="主图ID号，这是一个反范式设计，有一定的冗余" prop="mainImgUrl">
          <el-input v-model="form.mainImgUrl" placeholder="请输入主图ID号，这是一个反范式设计，有一定的冗余" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listGoods, delGoods, addGoods, updateGoods, changeGoodsStatus } from '@/api/goods/goods'
import { categoryTree } from '@/api/goods/category'

export default {
  name: "Goods",
  data() {
    return {
      //分类搜索下拉数据
      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品管理表格数据
      goodsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        goodsName: null,
        categoryId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        goodsName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  watch: {
    '$route.query.refresh'(newVal) {
      if (newVal) {
        this.getList();
        // 如果不想在URL中保留这个参数，可以重定向到没有它的URL
        this.$router.replace({ name: 'Goods', query: {} });
      }
    },
  },
  methods: {
    /** 查询商品管理列表 */
    getList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.total = response.data.total??0;
        if(this.total>0){
          this.goodsList = response.data.data.map(item => ({
            ...item, // 复制当前项的所有属性
            mainImgUrl: process.env.VUE_APP_BASE_API + item.mainImgUrl, // 拼接新的图片 URL
            type: "普通商品",
          }));
        }else{
          this.goodsList = response.data.data;
        }
        this.loading = false;
        this.getCategoryTreeList();
      });
    },

    /** 查询商品管理列表 */
    getCategoryTreeList() {
      categoryTree().then(response => {
        this.options = response.data
      });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    cascaderHandleQuery(e){
      // 安全地获取数组e的最后一个元素
      const lastElement = e.slice(-1)[0];
      this.queryParams.categoryId = lastElement;
    },
    // 表单重置
    reset() {
      this.form = {
        goodsId: null,
        goodsSn: null,
        goodsName: null,
        goodsUnit: null,
        goodsSpecification: null,
        sellingPrice: null,
        costPrice: null,
        price: null,
        stock: null,
        weight: null,
        volume: null,
        goodsDetails: null,
        quantitySold: null,
        orderNum: null,
        goodsRecommend: null,
        goodsViews: null,
        numberVisitors: null,
        numberOrdered: null,
        numberFavorites: null,
        status: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        mainImgUrl: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.goodsId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      const goodsId = 0;
      this.$router.push("/goods/goods-data/goodsId/" + goodsId);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const goodsId = row.goodsId || this.ids
      this.$router.push("/goods/goods-data/goodsId/" + goodsId);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.goodsId != null) {
            updateGoods(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addGoods(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const goodsIds = row.goodsId || this.ids;
      this.$modal.confirm('是否确认删除商品管理编号为"' + goodsIds + '"的数据项？').then(function() {
        return delGoods(goodsIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('admin/SGoods/exportGoods', {
        ...this.queryParams
      }, `goods_${new Date().getTime()}.xlsx`)
    },
    // 商品状态修改
    handleStatusChange(row) {
      console.log(row)
      let text = row.status === "0" ? "上架" : "下架";
      this.$modal.confirm('确认要"' + text + '""' + row.goodsName + '"商品吗？').then(function() {
        return changeGoodsStatus(row.goodsId, row.status);
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
  }
};
</script>
<style>
.demo-table-expand {
  padding-left: 100px;
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #606266;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 30%!important;
}
.demo_label__label__font{
  width: 100px!important;
}
.demo_label__label__font__span {
  font-size: 13px;
  margin-top: 10px;
  line-height: 16px;
}
.demo_label__label__font__span__width-250{
  width: 245px;
}
.demo_label__label__font label {
  font-size: 13px!important;
  font-weight: normal;
}
.width-95 label {
  width: 95px!important;
}
.width-70 label {
  width: 70px!important;
}
.width-55 label {
  width: 55px!important;
}
.width-45 label {
  width: 45px!important;
}
</style>
